<template>
  <div id="app">
    <!-- <h1>我的购物车</h1> style="width: 1200px"-->
    <el-card>
      <el-tabs v-model="initData.activeName">
        <!-- 添加商品 -->
        <el-tab-pane label="添加商品" name="first">
          <div class="app-container">
            <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
              <el-form-item label="品名" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入品名" clearable size="small"
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="款号" prop="itemNum">
                <el-input v-model="queryParams.itemNum" placeholder="请输入款号" clearable size="small"
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="尺码" prop="sizeNum">
                <el-input v-model="queryParams.sizeNum" placeholder="请输入尺码" clearable size="small"
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-table v-loading="loading" :data="stockList">
              <el-table-column width="55" align="center" />
              <el-table-column label="主键" align="center" prop="id" v-if="false" />
              <el-table-column label="图片" prop="imageUrlPre">
                <template slot-scope="scope" width="90">
                  <!-- <img style="width:80px;height:80px;border:none;" :src="uploadImgUrl+scope.row.imageUrlPre"> -->
                  <ImagePreview style="width:120px;height:80px;border:none;" :src="scope.row.imageUrlPre" />
                </template>
              </el-table-column>
              <el-table-column label="品名" align="center" prop="name" />
              <el-table-column label="款号" align="center" prop="itemNum" />
              <el-table-column label="尺码" align="center" prop="sizeNum" />
              <el-table-column label="单价" align="center" prop="price" />
              <el-table-column label="成本" v-if="false" align="center" prop="cost" />
              <el-table-column label="库存量" align="center" prop="count" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button size="mini" type="primary" @click="handleAdd(scope.row, scope.$index)">添加</el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize" @pagination="getList" />
          </div>
        </el-tab-pane>
        <!-- 购物车商品 -->
        <el-tab-pane label="结算商品" name="second">
          <el-table :data="initData.addedGoods" @select="handleSum" @select-all="handleSum" ref="multipleTable">
            <!-- 复选框 -->
            <el-table-column type="selection"></el-table-column>
            <el-table-column prop="name" label="名称"></el-table-column>
            <el-table-column prop="itemNum" label="款号"> </el-table-column>
            <el-table-column prop="sizeNum" label="尺码"> </el-table-column>
            <el-table-column prop="count" label="库存" v-if="false"></el-table-column>
            <el-table-column prop="id" label="库存id/商品的id" v-if="false"></el-table-column>
            <el-table-column label="数量" prop="countN" width="280">
              <!-- 使用计数器来添加数量，绑定表格数据行对应的count -->
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.countN" @change="(currentValue, oldValue) => checkcountN(scope.row)"
                  :min="1" :max="10"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="单价">
              <template slot-scope="prices">
                <span>￥{{ prices.row.price }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="money" label="金额">
              <template slot-scope="moneys">
                <span>￥{{ moneys.row.price * moneys.row.countN }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="danger" @click="handleDelete(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin: 20px">
            <el-row>
              <el-col :span="6">
                <div class="grid-content bg-purple">
                  总价：<span style="color: red">￥{{ disCountAfterSum }}</span>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="grid-content bg-purple">
                  折扣：<el-select v-model="initData.disCount" placeholder="请选择折扣" clearable size="mini">
                    <el-option v-for="dict in dict.type.sys_discount_value" :key="dict.value" :label="dict.label"
                      :value="dict.value" />
                  </el-select>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="grid-content bg-purple" v-if="initData.isShowDiscount">
                  会员：<span style="color: red">{{ initData.userName }}</span>
                </div>
              </el-col>

              <el-col :span="6">
                <div class="grid-content bg-purple">
                  <el-button type="primary" plain size="mini" @click="memberAdd">选择会员</el-button>
                </div>
              </el-col>
            </el-row>
          </div>
          <div style="margin: 20px">
            <el-row type="flex" justify="end">
              <el-col :span="24">
                <el-button style="text-align: right" size="max" type="danger" @click="handlePayRecord()">结算</el-button>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 表格对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form :model="queryMembers" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="手机号" prop="phoneNum">
          <el-input v-model="queryMembers.phoneNum" placeholder="请输入手机号" clearable size="small"
            @keyup.enter.native="handleQueryMember" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="queryMembers.name" placeholder="请输入姓名" clearable size="small"
            @keyup.enter.native="handleQueryMember" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryMember">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQueryMember">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="memberList" @row-dblclick="fillMemberInfo">
        <!-- <el-table v-loading="loading" :data="memberList" @selection-change="handleSelectionChange"> -->
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="主键" align="center" prop="id" v-if="false" />
        <el-table-column label="姓名" align="center" prop="name" />
        <el-table-column label="手机号" align="center" prop="phoneNum" />
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryMembers.pageNum"
        :limit.sync="queryMembers.pageSize" @pagination="memberList" />
    </el-dialog>
  </div>
</template>

<script>
import { listStock } from "@/api/system/stock";
import { listMember } from "@/api/system/member";
import { getToken } from "@/utils/auth";
import {
  listPayrecord,
  getPayrecord,
  delPayrecord,
  addPayrecord,
  updatePayrecord,
  exportPayrecord,
} from "@/api/system/payrecord";

export default {
  dicts: ["sys_discount_value"],
  data() {
    return {
      //=================================
      initData: {
        isShowDiscount: false,
        //折扣
        disCount: null,
        userName: "",
        userId: "",

        // 结算记录表格数据
        payrecordObj: {},
        // 结算记录(从)表格数据
        sysPayRecordSlaveList: [],
        //单价*数量
        sum: 0,
        //成本* 数量
        costSum: 0,

        //保存

        activeName: "first",
        // 添加进购物车的商品数组
        addedGoods: [],
      },

      //===============
      member: {
        id: null,
        name: null,
      },
      //获取会员用户信息
      memberList: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存表格数据
      stockList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,

        name: null,
        itemNum: null,
        sizeNum: null,
        price: null,
        cost: null,
        count: null,
        currentCount: null,
      },
      //查询vip用户
      queryMembers: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        phoneNum: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      //=================================
    };
  },
  created() {
    this.getList();
    this.getMemberList();
  },
  methods: {
    //为页面中的会员标签处赋值
    fillMemberInfo(row) {
      this.initData.userName = row.name;
      this.initData.userId = row.id;
      this.initData.isShowDiscount = true;
      //把页面关闭
      this.open = false;
    },

    //打开会员界面
    memberAdd() {
      this.open = true;
      this.title = "选择会员";
    },

    checkcountN(row) {
      this.initData.addedGoods.forEach((item) => {
        if (item.countN > item.count) {
          this.$modal.msgError(
            item.name + ": 购买数量已经大于库存数量,请先到库存中心录入后再结算"
          );
          item.countN = 1;
        }
      });
      this.handleSum();
    },
    // 计算总额
    handleSum() {
      this.initData.sum = 0;
      this.initData.costSum = 0;
      this.$nextTick(() => {
        // console.log(this.$refs.multipleTable.selection);
        // this.$refs.multipleTable.selection获取被选中的行
        this.$refs.multipleTable.selection.forEach((item) => {
          //若购买数量大于库存数量了，禁止往下执行
          let continueTo = true;
          if (item.countN > item.count) {
            this.$modal.msgError(
              "购买数量已经大于库存数量,请先到库存中心录入后再结算"
            );
            continueTo = false;
          }
          if (continueTo) {
            this.initData.sum += item.price * item.countN;
            //成本 * 购买数量
            this.initData.costSum += item.cost * item.countN;
          }
        });
      });
    },

    // },
    // 删除操作
    handleDelete(i) {
      this.initData.addedGoods.splice(i, 1);
      this.handleSum();
    },
    //結算处理
    handlePayRecord() {
      this.initData.addedGoods.forEach((item) => {
        //先添加从表数据
        let slaveObj = {};
        //结算日期
        slaveObj.payDate = new Date();
        //购买数量
        slaveObj.subCount = item.countN;
        //库存id
        slaveObj.stockId = item.id;
        //当时折扣
        slaveObj.currentDiscount =
          this.initData.disCount != null
            ? this.initData.disCount != ""
              ? this.initData.disCount
              : 1
            : 1;
        //是否有效
        slaveObj.effect = 1;
        this.initData.sysPayRecordSlaveList.push(slaveObj);
      });
      //添加主表数据
      this.initData.payrecordObj.userId = this.initData.userId;
      this.initData.payrecordObj.userName = this.initData.userName;

      //是否有效
      this.initData.payrecordObj.effect = 1;
      //结算日期
      this.initData.payrecordObj.payDate = new Date();
      this.initData.payrecordObj.sysPayRecordSlaveList =
        this.initData.sysPayRecordSlaveList;

      this.$prompt("请输入实际开单价格", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputValidator(value) {
          let pattern = /^[1-9][0-9]*$/;
          if (!pattern.test(value)) {
            return false;
          }
        },
        inputErrorMessage: "只能输入数字金额",
      })
        .then(({ value }) => {
          //结算金额
          //把实际输入的开单就价格，赋值给paymoney 

          this.initData.payrecordObj.payMoney = value;
          this.initData.payrecordObj.profit = value - this.initData.costSum;
          //新增支付记录
          addPayrecord(this.initData.payrecordObj)
            .then((response) => {
              this.$modal.msgSuccess("结算成功");
              this.open = false;
              Object.assign(
                this.$data.initData,
                this.$options.data.call(this).initData
              );
              //结算成功后，要刷新一下库存接口
              this.getList();
            })
            .catch(() => {
              Object.assign(
                this.$data.initData,
                this.$options.data.call(this).initData
              );
              this.$modal.msgError("结算失败");
            });
        })
        .catch(() => {
          Object.assign(
            this.$data.initData,
            this.$options.data.call(this).initData
          );
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    // 添加操作
    handleAdd(row, i) {
      let flag = false;
      this.initData.addedGoods.forEach((item) => {
        if (item.id == row.id) {
          if (item.countN + 1 > row.count) {
            this.$modal.msgError(
              "购买数量已经大于库存数量,请先到库存中心录入后再结算"
            );
            flag = true;
            return false;
          }
          item.countN++;
          flag = true;
        }
      });
      let obNew = {};
      obNew["id"] = row.id;
      obNew["countN"] = 1;
      obNew["name"] = row.name;
      obNew["price"] = row.price;
      obNew["count"] = row.count; //库存
      obNew["itemNum"] = row.itemNum; //款号
      obNew["sizeNum"] = row.sizeNum; //尺寸
      obNew["cost"] = row.cost; //成本

      if (!flag) this.initData.addedGoods.push(obNew);
      //1每次在页面上添加前，先把选中的清除
      this.$refs.multipleTable.clearSelection();
      //2然后再全选中
      this.$refs.multipleTable.toggleAllSelection();
      //3激活添加页面
      this.initData.activeName = "second";
    },
    //=======================================
    /** 查询库存列表 */
    getList() {
      this.loading = true;
      listStock(this.queryParams).then((response) => {
        this.stockList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    //查询用户
    getMemberList() {
      this.loading = true;
      listMember(this.queryMembers).then((response) => {
        this.memberList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        itemNum: null,
        sizeNum: null,
        price: null,
        cost: null,
        count: null,
      };
      //把这个引用的标签中的form清空
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 会员搜索按钮操作 */
    handleQueryMember() {
      this.queryMembers.pageNum = 1;
      this.getMemberList();
    },
    /** 会员重置按钮操作 */
    resetQueryMember() {
      this.resetForm("queryForm");
      this.handleQueryMember();
    },
  },
  computed: {
    //计算折后价格，渲染到页面上
    disCountAfterSum: function () {
      let disCount = 1;
      if (this.initData.disCount != null && this.initData.disCount != "") {
        disCount = this.initData.disCount;
      }
      return Math.floor(this.initData.sum * disCount);
    },
    //支付后获取的利润
    profit: function () {
      //需要支付的价格-总成本 = 利润；
      return this.disCountAfterSum - this.initData.costSum;
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
